<template>
  <div style="padding: 0px; overflow-x: hidden; overflow-y: hidden">
    <div :style="{ width: offsetwidth + 'px' }" style="height: 950px">
      <el-amap
        vid="amapDemo"
        :center="center"
        :amap-manager="amapManager"
        :zoom="zoom"
        :events="events"
        class="amap-demo"
      >
        <el-amap-marker
          vid="component-marker"
          ref="marker"
          v-if="marker.position.length != 0"
          :position="marker.position"
          :events="marker.events"
          :visible="marker.visible"
          :icon="marker.icon"
        ></el-amap-marker>

        <template v-if="eventMarkersVisible">
          <el-amap-marker
            vid="event-marker"
            ref="marker_event"
            v-for="(marker, index) in eventMarkers"
            :key="'e' + index"
            :position="marker.position"
            :events="marker.events"
            :icon="marker.icon"
          ></el-amap-marker>
        </template>

        <template v-if="companyMarkersVisible">
          <el-amap-marker
            vid="company-marker"
            ref="marker_company"
            v-for="(marker, index) in companyMarkers"
            :key="'c' + index"
            :position="marker.position"
            :events="marker.events"
            :icon="marker.icon"
          ></el-amap-marker>
        </template>

        <template v-if="userMarkersVisible">
          <el-amap-marker
            vid="user-marker"
            ref="marker_user"
            v-for="(marker, index) in userMarkers"
            :key="'u' + index"
            :position="marker.position"
            :events="marker.events"
            :icon="marker.icon"
          ></el-amap-marker>
        </template>

				<!-- 点击点位出现窗口 -->
        <el-amap-info-window
          :position="infoDlg.position"
          :visible="infoDlg.visible"
        >
          <div>
            <div
              style="
                padding: 10px;
                font-weight: bold;
                border-bottom: 1px solid #32cec1;
              "
            >
              {{ infoDlg.title }}
            </div>
            <div style="padding: 10px">
              <div v-for="(item, index) in infoDlg.msg" :key="index">
                {{ item }}
              </div>
              <el-button
                type="primary"
                @click="onClick(infoDlg.info)"
                size="mini"
                class="mt5"
                style="width: 140px; background: rgba(10, 137, 145, 1)"
                v-if="infoDlg.info.what == 'question'"
                >查看详情</el-button
              >
            </div>
          </div>
        </el-amap-info-window>

        <el-amap-polygon
          v-for="(polygon, index) in polygons"
          :vid="index"
          :path="polygon.path" :key="index"
          :fillOpacity="polygon.fillOpacity"
        ></el-amap-polygon>

        <el-amap-polygon
          :path="pathPolygon.path"
          fillOpacity="0.3"
          fillColor="#FFAA00"
        ></el-amap-polygon>
      </el-amap>
    </div>

    <div class="a11">
      <!-- 地图上的左边图标 -->
      <template v-if="state == '1'">
        <div
          style="
            width: 492px;
            height: 38px;
            margin-top: 4px;
            margin-bottom: 2px;
            text-align: center;
          "
        >
          <div
            style="
              width: 80px;
              height: 30px;
              float: left;
              background: #0a8991;
              padding-top: 7px;
              color: #fff;
              cursor: pointer;
            "
            @click="open"
          >
            <img src="@/assets/right.png" class="mt4" />
          </div>

          <div
            :class="{ active: what == 'question' }"
            class="btn1"
            @click="question"
          >
            服务日志
          </div>

          <div
            :class="{ active: what == 'grid' }"
            class="btn1"
            @click="grid"
          >
            网格
          </div>
<!--
          <div :class="{ active: what == 'user' }" class="btn1" @click="user">
            网格员
          </div>
          
			<div 
			:class="{active : what == 'company'}"
			class="btn1" 
			@click="company"
			>
				企业单位
			</div>

			<div 
			:class="{active : what == 'trajectory'}"
			class="btn1" 
			@click="trajectory"
			>
				网格员轨迹
			</div>
			-->
        </div>
      </template>
      <!-- 地图上的左边图标关闭 -->
      <template v-else>
        <div
          style="
            width: 492px;
            height: 38px;
            margin-top: 4px;
            margin-bottom: 2px;
            text-align: center;
          "
        >
          <div
            style="
              width: 80px;
              height: 30px;
              float: left;
              background: #0a8991;
              padding-top: 7px;
              color: #fff;
              cursor: pointer;
            "
            @click="open"
          >
            <img src="@/assets/left.png" class="mt4" />
          </div>
        </div>
      </template>

      <div
        v-if="dlg && state == '1'"
        v-show="showdlg"
        style="width: 492px;height: 900px;background: #0a5060;"
      >
			<!-- 
        <trajectory
          v-if="what == 'trajectory'"
          :treedata="treedata"
          v-on:playback="playback"
        ></trajectory>
			-->

        <question
          v-if="what == 'question'"
          :treedata="treedata"
          v-on:getpoint="getpoint"
          v-on:getpointList="getpointList"
        ></question>

        <user
          v-if="what == 'user'"
          :treedata="treedata"
          v-on:getpoint="getpoint"
        ></user>

				<!-- 
        <company
          v-if="what == 'company'"
          :treedata="treedata"
          v-on:getpoint="getpoint"
        ></company>
				-->

        <grid
          v-if="what == 'grid'"
          :treedata="treedata"
          v-on:showgrid="showgrid"
          v-on:getpoint="getpoint"
        ></grid>
      </div>
    </div>

    <div
      class="a12"
      v-if="dlg && state == '1'"
      v-show="showdlg"
      @click="changeDlg"
    >
      <template>
        <i class="el-icon-arrow-left"></i>
      </template>
    </div>

    <div
      class="a13"
      v-if="dlg && state == '1'"
      v-show="!showdlg"
      @click="changeDlg"
    >
      <template>
        <i class="el-icon-arrow-right"></i>
      </template>
    </div>

    <!-- 事件详情 -->
    <el-dialog
      :title="currentEvent.info.log_title"
      :visible.sync="eventDialogVisible"
      append-to-body
      width="900px"
    >
      <eventinfo :obj="currentEvent"></eventinfo>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import Vue from "vue";
import daterange from "@/components/daterange";
import trajectory from "./components/trajectory_1";
import question from "./components/question_1";
import user from "./components/user_1";
import company from "./components/company_1";
import grid from "./components/grid";
import eventinfo from "@/views/event/info_1";

import VueAMap from "vue-amap";

import { lazyAMapApiLoaderInstance } from "vue-amap";

let amapManager = new VueAMap.AMapManager();
//const loadPromise = VueAMap.lazyAMapApiLoaderInstance();

export default {
  name: "dashboard",

  data() {
    return {
      offsetwidth: document.documentElement.clientWidth - 70 - 3,
      offsetheight: document.documentElement.clientHeight - 70,

      state: "0",
      dlg: false,
      showdlg: true,

      what: "",

      current: {},

      treedata: [],

      pathSimplifierIns: null,

      infoWindow: null,

      zoom: 10,
      center: [123.412581, 41.805853],
      amapManager,

      marker: {
        position: [],
      },

      eventMarkers: [],
      userMarkers: [],
      companyMarkers: [],

      polygons: [],

      pathPolygon: {
        path: [],
      },

      task_type_label: ["", "紧急任务", "普通", "检查", "日常"],

      status_label: ["", "处理中", "已完成"],

      polygon: null,

      events: {
        init(o) {
          AMap.plugin("AMap.DistrictSearch", () => {
            // 创建行政区查询对象
            var district = new AMap.DistrictSearch({
              // 返回行政区边界坐标等具体信息
              extensions: "all",
              // 设置查询行政区级别为 区
              level: "district",
            });

            district.search("210100", (status, result) => {
              let polygon = new AMap.Polygon({
                path: result.districtList[0].boundaries,
                fillOpacity: 0,
                strokeWeight: 5,
              });

              polygon.setMap(o);

              o.setFitView(polygon);
              //o.setZoom(10);
              //this.initPolygon(result.districtList[0].boundaries);
              // this.polygon.path = ;
              // //新增状态，以上级中心点作为中心。
              // if(this.currentGrid.id == undefined){
              // 	this.center = [
              // 		result.districtList[0].center.lng,
              // 		result.districtList[0].center.lat
              // 	];
              // }
            });
          });
        },
      },

      infoDlg: {
        position: [123.434,41.8057],
        info: {},
        visible: false,
        title: "",
        msg: [],
      },

      eventDialogVisible: false,
      currentEvent: {
        info: {
          title: "",
        },
      },

      //未完成事件、在线人员 显示情况
      eventMarkersVisible: true,
      userMarkersVisible: true,
      companyMarkersVisible: false,
    };
  },

  props: {},

  components: {
    daterange,
    trajectory,
    question,
    user,
    company,
    grid,
    eventinfo,
  },

  computed: {
    ...mapGetters({
      c: "center",
      cc: "cityCode",
    }),
  },

  methods: {
    open() {
      this.state = this.state == "1" ? "0" : "1";
    },

    close() {
      this.state = "0";
    },

    question() {
      this.current = {
        name: "服务日志",
      };
      this.what = "question";
      this.dlg = true;
      this.showdlg = true;
      this.clearAll();
      this.marker.visible = false;
      this.eventMarkersVisible = true;
      this.userMarkersVisible = false;
      // this.companyMarkersVisible = false;
    },
    user() {
      console.log("user");
      this.current = {
        name: "网格员",
      };
      this.what = "user";
      this.dlg = true;
      this.showdlg = true;

      this.clearAll();

      this.marker.visible = false;
      this.eventMarkersVisible = false;
      this.userMarkersVisible = true;
      this.companyMarkersVisible = false;
    },
    trajectory() {
      this.current = {
        name: "网格员轨迹",
      };
      this.what = "trajectory";
      this.dlg = true;
      this.showdlg = true;
    },
    grid() {
      this.current = {
        name: "网格列表",
      };
      this.what = "grid";
      this.dlg = true;
      this.showdlg = true;
    },

    closeDlg() {
      this.dlg = false;
    },

    init() {
      this.$http({
        fun: "onlineList",
        grid_id: 88888,
        cb: (res) => {
          console.log("onlineList");
          this.onlineList = res;
        },
      });
    },

    playback(para, gridinfo) {
      console.log("playback");
      console.log(para);
      console.log("gridinfo");
      console.log(gridinfo);

      this.marker.visible = false;
      this.eventMarkersVisible = false;
      this.userMarkersVisible = false;
      this.companyMarkersVisible = false;

      this.clearAll();

      this.$http({
        fun: "userTrajectory",
        ...para,
        cb: (res) => {
          if (res.length == 0) {
            this.$message.error("没有数据");
            return;
          }
          let arr = [];
          let time = [];
          res.forEach((item) => {
            arr.push([item.longitude, item.latitude]);
            time.push(item.create_time);
          });
          this.setPathSimplifier(arr, para.name, time);
        },
      });

      if (gridinfo.mapinfo != undefined && gridinfo.mapinfo != "") {
        //手画的网格
        if (parseInt(gridinfo.type) > 1) {
          const obj = eval('('+gridinfo.mapinfo+')') // JSON.parse();
          this.pathPolygon.path = obj.path;
        } else {
          AMap.plugin("AMap.DistrictSearch", () => {
            // 创建行政区查询对象
            var district = new AMap.DistrictSearch({
              // 返回行政区边界坐标等具体信息
              extensions: "all",
              // 设置查询行政区级别为 区
              level: "district",
            });

            district.search(eval('('+gridinfo.mapinfo+')'), (status, result) => {
              console.log(result);
              this.pathPolygon.path = result.districtList[0].boundaries;
            });
          });
        }
      }
    },

    clearAll() {
      //把已有的点干掉。
      //this.marker.position = [];
      //窗体干掉
      if (this.infoWindow != null) {
        this.infoWindow.close();
      }
      //如果有未销毁的轨迹,巡航器，全干掉。
      if (this.pathSimplifierIns != null) {
        this.pathSimplifierIns.setData([
          {
            name: "",
            path: [],
          },
        ]);
        this.pathSimplifierIns.clearPathNavigators();
      }

      //网格干掉
      if (this.polygon != null) {
        this.polygon.setPath([]);
      }

      this.pathPolygon.path = [];
    },

    setPathSimplifier(data, name, time) {
      const o = this.amapManager.getMap();

      AMapUI.loadUI(["misc/PathSimplifier"], (PathSimplifier) => {
        if (this.pathSimplifierIns == null) {
          this.pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            //autoSetFitView:false,
            map: o, //所属的地图实例

            getPath: function (pathData, pathIndex) {
              return pathData.path;
            },
            getHoverTitle: function (pathData, pathIndex, pointIndex) {
              if (pointIndex >= 0) {
                return (
                  pathData.name +
                  "，点：" +
                  pointIndex +
                  "/" +
                  pathData.path.length +
                  "， 时间 ：" +
                  pathData.time[pointIndex]
                );
              }
              return pathData.name + "，点数量" + pathData.path.length;
            },
            renderOptions: {
              renderAllPointsIfNumberBelow: 100, //绘制路线节点，如不需要可设置为-1
            },
          });
        }

        this.pathSimplifierIns.setData([
          {
            name: name,
            path: data,
            time,
          },
        ]);

        this.pathSimplifierIns.clearPathNavigators();

        let navg1 = this.pathSimplifierIns.createPathNavigator(0, {
          //loop: true, //循环播放
          speed: 120, //巡航速度，单位千米/小时
          pathNavigatorStyle: {
            width: 24,
            height: 24,
            content: PathSimplifier.Render.Canvas.getImageContent(
              "./person1.png",
              () => {
                this.pathSimplifierIns.renderLater();
              },
              () => {
                console.log("图片加载失败");
              }
            ),
            strokeStyle: null,
            fillStyle: null,
          },
        });

        navg1.start();
      });
    },

    changeDlg() {
      this.showdlg = !this.showdlg;
    },

    getpointList(data) {
      this.clearAll();
      console.log('点击表格后传过来的List值： ', data.results);
      this.eventMarkersVisible = false;
      this.userMarkersVisible = false;
      let res = data.results
      // this.companyMarkersVisible = false;
      this.eventMarkers = []

      if (res && res.length > 0) {
        
        res.forEach(item => {
          if (item.log_title) { 
            const info = {
              ...item,
              what: "question",
              lon: item.event_longitude,
              lat: item.event_latitude,
            };

            if (item.work_status == "1") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./event_doing.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "2") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark1.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "3") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark2.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "4") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark3.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "5") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark4.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "6") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark5.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "7") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark6.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "8") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./mark7.png",
              };
              this.eventMarkers.push(obj);
            } else if (item.work_status == "9") {
              let obj = {
                position: [item.event_longitude, item.event_latitude],
                events: {
                  click: () => {
                    this.clickMarker1(info);
                  },
                },
                visible: true,
                info,
                icon: "./event_see.gif",
              };
              this.eventMarkers.push(obj);
            }
          }
          this.eventMarkersVisible = true;
          console.log('eventMarkers ===================', this.eventMarkers)
          // this.$forceUpdate()
            // this.center = [parseFloat(item.event_longitude), parseFloat(item.event_latitude)];
        })
      }

    },

    getpoint(item) {
      this.clearAll();
      console.log('点击表格后传过来的： ', item);
      this.eventMarkersVisible = false;
      this.userMarkersVisible = false;
      // this.companyMarkersVisible = false;

      if (item.what == "user" || item.what == "question") {
        if (item.what == "question") {
          if (item.work_status == "1") {
            this.marker.icon = "./event_doing.png";
          } else if (item.work_status == "2") {
            this.marker.icon = "./mark1.png";
          } else if (item.work_status == "3") {
            this.marker.icon = "./mark2.png";
          } else if (item.work_status == "4") {
            this.marker.icon = "./mark3.png";
          } else if (item.work_status == "5") {
            this.marker.icon = "./mark4.png";
          } else if (item.work_status == "6") {
            this.marker.icon = "./mark5.png";
          } else if (item.work_status == "7") {
            this.marker.icon = "./mark6.png";
          } else if (item.work_status == "8") {
            this.marker.icon = "./mark7.png";
          } else if (item.work_status == "9") {
            this.marker.icon = "./event_see.gif";
          }
        } else if (item.what == "user") {
          this.marker.icon = "./user1.png";
        }
        this.marker.position = [item.lon, item.lat];
        this.marker.events = {
          click: () => {
            this.clickMarker1(item);
          },
        };

        this.marker["info"] = item;

        console.log(this.marker);

        this.marker.visible = true;
        // this.$nextTick(() => {
        // 	this.marker.visible = true;
        // });
      }

      this.center = [parseFloat(item.lon), parseFloat(item.lat)];
    },

    clickMarker(item) {
      if (this.marker.position.length == 0) {
        return;
      }
      const o = this.amapManager.getMap();

      AMapUI.loadUI(["overlay/SimpleInfoWindow"], (SimpleInfoWindow) => {
        if (this.infoWindow == null) {
          this.infoWindow = new SimpleInfoWindow({
            offset: new AMap.Pixel(0, -31),
          });
        }

        var msg = "";
        var title = "";

        const { what, lon, lat } = this.marker.info;

        if (what == "question") {
          const {
            question_title,
            release_name,
            grid_names,
            task_type,
            status,
            release_time,
            handler_grid_name,
          } = this.marker.info;

          title = question_title;

          msg =
            "上报人：" +
            release_name +
            "<br>" +
            "上报网格：" +
            grid_names +
            "<br>" +
            "任务类型：" +
            this.task_type_label[parseInt(task_type)] +
            "<br>" +
            "处理状态：" +
            this.status_label[parseInt(status)] +
            "<br>" +
            "创建时间：" +
            release_time; // + '<br>' +
          //'当前处理人：' + handler_grid_name ;
        } else if (what == "user") {
          const { name, mobile, company_name } = this.marker.info;

          title = name;

          msg =
            "人员名称：" +
            name +
            "<br>" +
            "联系电话：" +
            (mobile == undefined ? "" : mobile) +
            "<br>" +
            "所属网格：" +
            company_name;
        } else if (what == "company") {
          const {
            name,
            company_type_name,
            address,
            hb_name,
            hb_mobile,
            lxr_name,
            lxr_phone,
          } = this.marker.info;

          title = name;

          console.log(company_name);

          msg =
            "企业名称：" + name + "<br>" + "企业类型：" + company_type_name ==
            undefined
              ? ""
              : company_type_name + "<br>" + "企业地址：" + address == undefined
              ? ""
              : address +
                "<br>" +
                "环保联系人：" +
                hb_name +
                "<br>" +
                "环保联系人电话：" +
                hb_mobile +
                "<br>" +
                "联系人：" +
                (lxr_name == undefined ? "" : lxr_name) +
                "<br>" +
                "联系人电话：" +
                (lxr_phone == undefined ? "" : lxr_phone);
        }

        this.infoWindow.setInfoTitle(title);
        this.infoWindow.setInfoBody(msg);
        this.infoWindow.open(o, [lon, lat]);
      });
    },

    //点击初始化的点
    clickMarker1(item) {
      this.clearAll();
      console.log("点击初始化的点",item.log_title);
      const { what, lon, lat } = item;
      this.infoDlg.position = [lon, lat];
      this.infoDlg.info = item;
      this.infoDlg.msg = [];

      if (what == "question") {
        const {
          id,
					log_title,
					grid_names,
					log_info,
					work_status,
					work_status_name,
					work_obj_status,
					work_obj_status_name,
					log_status,
					log_status_name,
					STATUS,
					handler_grid_name,
					release_time,
					event_longitude,
					event_latitude,
					question_img,
					work_obj_name,
					work_obj_tel,
					responsibility_person,
					responsibility_person_mobile,
					release_name,
					create_time
        } = item;

        this.infoDlg.title = log_title;

				this.infoDlg.msg.push("上报人：" + release_name);
				this.infoDlg.msg.push("责任人：" + responsibility_person);
        this.infoDlg.msg.push("上报网格：" + grid_names);
        this.infoDlg.msg.push("工作类型：" + work_status_name);
        this.infoDlg.msg.push("创建时间：" + create_time);
      } else if (what == "user") {
        const { name, mobile, company_name } = item;
        // this.infoDlg.title = name;
        this.infoDlg.msg.push("人员名称：" + name);
        this.infoDlg.msg.push("联系电话：" + (mobile == undefined ? "" : mobile));
        this.infoDlg.msg.push("所属网格：" + company_name);
      } 
      this.center = [lon, lat];
      const o = this.amapManager.getMap();
      o.setZoom(15);
      this.infoDlg.visible = false;
      this.$nextTick(() => {
        this.infoDlg.visible = true;
      });
    },
    showgrid(item) {
      this.clearAll();
      console.log("网格变化范围===============： ", item);
      const map = this.amapManager.getMap();
      if (item.mapinfo == undefined) {
        if (item.id != "1") {
          this.$message.error("没有数据");
        }
        return;
      }

      if (this.polygon == null) {
        this.polygon = new AMap.Polygon({
          path: [],
          strokeColor: "#FF33FF",
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: "#1791fc",
          zIndex: 50,
        });
        map.add(this.polygon);
      }

      if (parseInt(item.type) > 2) {
        const obj = eval('('+item.mapinfo+')') //JSON.parse(item.mapinfo);
        this.polygon.setPath(obj.path);
        map.setFitView([this.polygon]);
      } else {
        AMap.plugin("AMap.DistrictSearch", () => {
          // 创建行政区查询对象
          var district = new AMap.DistrictSearch({
            // 返回行政区边界坐标等具体信息
            extensions: "all",
            // 设置查询行政区级别为 区
            level: "district",
          });

          district.search(item.mapinfo.split(',')[0], (status, result) => {
            console.log("沈阳区级别的就别画了");
            this.polygon.setPath(result.districtList[0].boundaries);
            map.setFitView([this.polygon]);
          });
        });
      }
    },

    //初始化所有日志，人员。
    init1() {
      this.$http({
        fun: "eventNoList",
        grid_id: "88888",
        cb: (res) => {
          res.forEach((item) => {
            const info = {
              ...item,
              what: "question",
              lon: item.event_longitude,
              lat: item.event_latitude,
            };

						if (item.work_status == "1") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./event_doing.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "2") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark1.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "3") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark2.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "4") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark3.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "5") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark4.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "6") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark5.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "7") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark6.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "8") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./mark7.png",
							};
							this.eventMarkers.push(obj);
						} else if (item.work_status == "9") {
							let obj = {
								position: [item.event_longitude, item.event_latitude],
								events: {
									click: () => {
										this.clickMarker1(info);
									},
								},
								visible: true,
								info,
								icon: "./event_see.gif",
							};
							this.eventMarkers.push(obj);
						}
          });
        }
      });

      this.$http({
        fun: "onlineNoList",
        grid_id: "1",
        cb: (res) => {
          console.log("初始化人员数据");
          console.log(res);
          res.forEach((item) => {
            const info = {
              ...item,
              what: "user",
              lon: item.now_longitude,
              lat: item.now_latitude,
            };

            let obj = {
              position: [item.now_longitude, item.now_latitude],
              events: {
                click: () => {
                  this.clickMarker1(info);
                },
              },
              visible: true,
              info,
              icon: "./user1.png",
            };
            this.userMarkers.push(obj);
          });

          console.log("this.userMarkers");
          console.log(this.userMarkers);
        },
      });

      this.$http({
        fun: "grideList",
        cb: (res) => {
          //mapinfo type > 2 的，存的是点数组，小于等于2的需要查询。
          let xiaoyu2 = [];
          let dayu2 = [];
          res.forEach((item) => {
            if (item.mapinfo != undefined && item.mapinfo != "") {
              if (parseInt(item.type) > 2) {
                dayu2.push(eval('('+item.mapinfo+')'));
              } else {
                xiaoyu2.push(item.mapinfo);
              }
              // const map = this.amapManager.getMap();
              // if (item.mapinfo == undefined) {
              //   if (item.id != "1") {
              //     this.$message.error("没有数据");
              //   }
              //   return;
              // }
              // if (this.polygon == null) {
              // // let polygon = new AMap.Polygon({
              // //   path: result.districtList[0].boundaries,
              // //   fillOpacity: 0,
              // //   strokeWeight: 5,
              // // });
              //   this.polygon = new AMap.Polygon({
              //     path: [],
              //     // strokeColor: "#FF33FF",
              //     strokeWeight: 5,
              //     // strokeOpacity: 0.2,
              //     fillOpacity: 0,
              //     // fillColor: "#1791fc",
              //     // zIndex: 50,
              //   });
              //   map.add(this.polygon);
              // }
              // if (parseInt(item.type) > 2) {
              //   const obj = eval('('+item.mapinfo+')') //JSON.parse(item.mapinfo);
              //   this.polygon.setPath(obj.path);
              //   map.setFitView([this.polygon]);
              // } else {
              //   AMap.plugin("AMap.DistrictSearch", () => {
              //     // 创建行政区查询对象
              //     var district = new AMap.DistrictSearch({
              //       // 返回行政区边界坐标等具体信息
              //       extensions: "all",
              //       // 设置查询行政区级别为 区
              //       level: "district",
              //     });

              //     district.search(item.mapinfo.split(',')[0], (status, result) => {
              //       console.log("沈阳区级别的就别画了");
              //       this.polygon.setPath(result.districtList[0].boundaries);
              //       map.setFitView([this.polygon]);
              //     });
              //   });
              // }
            }
          });
          this.xiaoyu2grid(xiaoyu2);
          this.dayu2grid(dayu2);
        },
      });
    },

    //小于2的画网格
    xiaoyu2grid(adcodes) {
			// console.log('xxxxxxxxx:', adcodes)
      lazyAMapApiLoaderInstance.load().then(() => {
        AMap.plugin("AMap.DistrictSearch", () => {
          // 创建行政区查询对象
          var district = new AMap.DistrictSearch({
            // 返回行政区边界坐标等具体信息
            extensions: "all",
            // 设置查询行政区级别为 区
            level: "district",
          });
          adcodes.forEach((adcode) => {
            district.search(adcode, (status, result) => {
              let path = [];
              path = result.districtList[0].boundaries;
              this.polygons.push({
                path,
                fillOpacity: 0,
              });
            });
          });
        });
      });
    },

    dayu2grid(data) {
      data.forEach((item) => {
        this.polygons.push({
          path: item.path,
          fillOpacity: 0,
        });
      });
    },
		// 加载沈阳地图
    initPage() {
      const map = this.amapManager.getMap();

      //创建一个实例
      var districtExplorer = new DistrictExplorer({
        map, //关联的地图实例
      });

			// 沈阳地图
      var adcode = ["210100", "210102"];

      districtExplorer.loadMultiAreaNodes(adcode, (error, areaNode) => {
        if (error) {
          return;
        }
        //绘制载入的区划节点
        this.renderAreaNode(districtExplorer, areaNode);
      });
    },

    renderAreaNode(districtExplorer, areaNodes) {
      //清除已有的绘制内容
      districtExplorer.clearFeaturePolygons();

      //just some colors
      var colors = [
        "#3366cc",
        "#dc3912",
        "#ff9900",
        "#109618",
        "#990099",
        "#0099c6",
        "#dd4477",
        "#66aa00",
      ];

      areaNodes.forEach((areaNode) => {
        //绘制子级区划
        // districtExplorer.renderSubFeatures(areaNode, (feature, i) => {

        // 	var fillColor = colors[i % colors.length];
        // 	var strokeColor = colors[colors.length - 1 - i % colors.length];

        // 	return {
        // 		cursor: 'default',
        // 		bubble: true,
        // 		strokeColor: strokeColor, //线颜色
        // 		strokeOpacity: 1, //线透明度
        // 		strokeWeight: 1, //线宽
        // 		fillColor: fillColor, //填充色
        // 		fillOpacity: 0.35, //填充透明度
        // 	};
        // });

        //绘制父级区划，仅用黑色描边
        districtExplorer.renderParentFeature(areaNode, {
          cursor: "default",
          bubble: true,
          strokeColor: "black", //线颜色
          fillColor: null,
          strokeWeight: 3, //线宽
        });
      });

      //更新地图视野以适合区划面
      //map.setFitView(districtExplorer.getAllFeaturePolygons());
    },

    //查看事件详情
    onClick(item) {
      this.$http({
        fun: "eventInfo",
        id: item.id,
        cb: (res) => {
          // this.$http({
          //   fun: "flowList",
          //   id: item.id,
          //   cb: (res1) => {
          //     console.log(res);
          //     console.log(res1);

          //     // res1.forEach(item => {
          //     // 	if(item.params == undefined || item.params == ''){
          //     // 		item['paramsobj'] = {
          //     // 			content : '',
          //     // 		};
          //     // 	}else{
          //     // 		item['paramsobj'] = JSON.parse(item.params);
          //     // 	}
          //     // })

          //     // this.currentEvent = {
          //     // 	info : {
          //     // 		...res,
          //     // 		imgs : res.question_img ? res.question_img.split(',') : [],
          //     // 		videos : res.question_video ? res.question_video.split(',') : [],
          //     // 	},
          //     // 	flow : res1,

          //     // };
          //     // console.log(this.currentEvent);
          //     // this.activeName2 = 'first';
          //     // this.eventDialogVisible = true;

          //     res1.forEach((item1) => {
          //       if (item1.params) {
          //         item1["imgs"] = [];
          //         item1["videos"] = [];
          //         item1.params.forEach((item) => {
          //           if (
          //             item.type == "img" &&
          //             item.value != null &&
          //             item.value != ""
          //           ) {
          //             item1["imgs"] = item.value.split(",");
          //           }
          //           if (
          //             item.type == "video" &&
          //             item.value != null &&
          //             item.value != ""
          //           ) {
          //             item1["videos"] = item.value.split(",");
          //           }
          //         });
          //       }
          //     });  
          //   },
          // });
				
					this.currentEvent = {
						info: {
							...res,
						},
						flow: [],
					};
					console.log(this.currentEvent);
					this.activeName2 = "first";
					this.eventDialogVisible = true;
				},
      });
		},
		initGrid() {
			this.$http({
				fun: "grideList",
				cb: (res) => {
					const result = this.$util.transData(res, "id", "parent_id", "children");
					console.log('grid list: ', result);
					this.treedata = result;
					// this.treedata.unshift({
					// 	name : '全部网格',
					// 	id : 1,
					// });
				},
			});
		}
  },
  watch: {},
  mounted() {
    this.init();

    this.initGrid();

		this.init1();
		
		// this.initPage()

    // this.center = this.c;
  },
};
</script>

<style scope>
.amap-wrapper {
  width: 500px;
  height: 500px;
}

.a11 {
  position: absolute;
  /*background-color: #2092ab;*/
  /*padding: 0 10px;*/
  width: 492px;
  /*height: 940px;*/
  top: 105px;
  left: 35px;
}

.a12,
.a13 {
  position: absolute;
  top: 520px;
  width: 20px;
  height: 90px;
  background-image: url("../../assets/edge.png");
  color: #fff;
  text-align: center;
  padding-top: 72px;
  cursor: pointer;
}

.a12 {
  left: 526px;
}

.a13 {
  left: 34px;
}

.a2 {
  position: absolute;
  width: 414px;
  z-index: 999;
}

.a3 {
  width: 60px;
  height: 42px;
  background: #4bacc6;
  color: #fff;
  text-align: center;
  padding-top: 18px;
  margin-top: 10px;
  border-radius: 7px;
}

.a4 {
  width: 60px;
  height: 52px;
  background: #4bacc6;
  color: #fff;
  text-align: center;
  padding-top: 8px;
  margin-top: 10px;
  border-radius: 7px;
}

.active {
  background-color: #27cebf !important;
}

.btn1 {
  width: 100px;
  height: 30px;
  float: left;
  background: #0a8991;
  margin-left: 3px;
  padding-top: 7px;
  color: #fff;
  cursor: pointer;
}
</style>
